package com.oppodowngrader;

import android.content.Context;
import android.util.Log;

import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 管理用于HTTPS拦截的证书
 */
public class CertificateManager {
    private static final String TAG = "CertificateManager";
    private static final String KEYSTORE_TYPE = "PKCS12";
    private static final String KEYSTORE_PASSWORD = "oppodowngrader";
    private static final String KEY_ALIAS = "oppodowngrader";
    private static final String CERT_SUBJECT = "CN=OPPO Downgrader CA, O=OPPO Downgrader, OU=OPPO Downgrader";
    private static final String SIGNATURE_ALGORITHM = "SHA256WithRSAEncryption";
    
    private final Context context;
    private KeyStore keyStore;
    private File keyStoreFile;
    
    static {
        Security.addProvider(new BouncyCastleProvider());
    }
    
    public CertificateManager(Context context) {
        this.context = context;
        try {
            keyStore = KeyStore.getInstance(KEYSTORE_TYPE);
            keyStoreFile = new File(context.getFilesDir(), "oppodowngrader.p12");
            
            if (keyStoreFile.exists()) {
                loadKeyStore();
            } else {
                createKeyStore();
            }
        } catch (Exception e) {
            Log.e(TAG, "初始化证书管理器失败", e);
        }
    }
    
    private void loadKeyStore() throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
        try (FileInputStream fis = new FileInputStream(keyStoreFile)) {
            keyStore.load(fis, KEYSTORE_PASSWORD.toCharArray());
            Log.d(TAG, "已加载现有密钥库");
        }
    }
    
    private void createKeyStore() throws Exception {
        keyStore.load(null, KEYSTORE_PASSWORD.toCharArray());
        
        // 生成RSA密钥对
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        
        // 创建自签名证书
        X509Certificate certificate = generateSelfSignedCertificate(keyPair);
        
        // 存储到密钥库
        Certificate[] certificateChain = new Certificate[] { certificate };
        keyStore.setKeyEntry(KEY_ALIAS, keyPair.getPrivate(), KEYSTORE_PASSWORD.toCharArray(), certificateChain);
        
        // 保存密钥库到文件
        try (FileOutputStream fos = new FileOutputStream(keyStoreFile)) {
            keyStore.store(fos, KEYSTORE_PASSWORD.toCharArray());
            Log.d(TAG, "已创建并保存新的密钥库");
        }
    }
    
    private X509Certificate generateSelfSignedCertificate(KeyPair keyPair) throws OperatorCreationException, CertificateException {
        X500Name subject = new X500Name(CERT_SUBJECT);
        BigInteger serialNumber = BigInteger.valueOf(System.currentTimeMillis());
        
        // 设置证书有效期为10年
        Date startDate = new Date(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1));
        Date endDate = new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(3650));
        
        X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(
                subject,
                serialNumber,
                startDate,
                endDate,
                subject,
                keyPair.getPublic()
        );
        
        ContentSigner signer = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM)
                .build(keyPair.getPrivate());
        
        return new JcaX509CertificateConverter()
                .setProvider(BouncyCastleProvider.PROVIDER_NAME)
                .getCertificate(certificateBuilder.build(signer));
    }
    
    public PrivateKey getPrivateKey() {
        try {
            return (PrivateKey) keyStore.getKey(KEY_ALIAS, KEYSTORE_PASSWORD.toCharArray());
        } catch (Exception e) {
            Log.e(TAG, "获取私钥失败", e);
            return null;
        }
    }
    
    public X509Certificate getCertificate() {
        try {
            return (X509Certificate) keyStore.getCertificate(KEY_ALIAS);
        } catch (Exception e) {
            Log.e(TAG, "获取证书失败", e);
            return null;
        }
    }
}